package task

import (
	"errors"
	"k8s-admin/dao/task"
	"k8s-admin/global"
	"k8s-admin/models"
	"k8s-admin/utils"
	"strconv"
)

type TimerInterface interface {
	Create(req *models.TimerReq) error
	List() (*models.TimerRes, error)
	StartTimer(timerNummber string) (map[string]interface{}, error)
	// HistoryLists() (*models.TaskRes, error)
	// Delete(TaskNumber string) error
	// Update(TasksNumber string, req *models.TaskReq) error
}

type TimerInfo struct {
}

func NewTimerInterface() TimerInterface {
	return &TimerInfo{}
}
func (z *TimerInfo) Create(req *models.TimerReq) error {
	err := task.NewInterfaceTimers().Create(req)
	if err != nil {
		global.TPLogger.Error(err)
		return errors.New("定时任务创建失败")
	} else {
		return nil
	}
}

func (z *TimerInfo) List() (*models.TimerRes, error) {
	list, err := task.NewInterfaceTimers().List()
	if err != nil {
		global.TPLogger.Error(err)
		return nil, errors.New("数据加载失败")
	} else {
		return list, nil
	}

}

func (z *TimerInfo) StartTimer(timerNummber string) (map[string]interface{}, error) {
	timer, err := task.NewInterfaceTimers().StartTimer(timerNummber)
	if err != nil {
		global.TPLogger.Error(err)
		return nil, errors.New("定时任务启动失败")
	} else {
		PeriodTime, _ := strconv.Atoi(timer.PeriodTime)
		go func() {
			utils.TimeTask(int64(PeriodTime), timer.ShellExec, timer.TimerNumber, int(timer.CronID), timer.ID)
			// 获取当前携程ID
			//  := os.Getpid()
		}()
		return nil, nil

	}
}
